//
//  BBNetWorkService.swift
//  BaibuSeller
//
//  Created by 符艺柏 on 2019/12/17.
//  Copyright © 2019 whawhawhat. All rights reserved.
//

import UIKit
import Alamofire
import HandyJSON

class BBBaseModel: HandyJSON {
    required init() {}
    
    func mapping(mapper: HelpingMapper) {   //自定义解析规则，日期数字颜色，如果要指定解析格式，子类实现重写此方法即可
        //        mapper <<<
        //            date <-- CustomDateFormatTransform(formatString: "yyyy-MM-dd")
        //
        //        mapper <<<
        //            decimal <-- NSDecimalNumberTransform()
        //
        //        mapper <<<
        //            url <-- URLTransform(shouldEncodeURLString: false)//
        //        mapper <<<
        //            data <-- DataTransform()
        //
        //        mapper <<<
        //            color <-- HexColorTransform()
    }
}

enum ErrorCodeType: Int {

    // swiftlint:disable identifier_name

    case requestFaile = 0
    case IllegalParameter = 2
    case versionUpdate = 3
    case unauthorized = 100
    case accountPasswordError = 101
    case accountAbnormal = 102
    case multiDeviceLogin = 103
    case loginInformationOutdate = 104
    case auditInformation = 105
    case userBanned = 107
    // swiftlint:enable identifier_name
}

enum RequestDataType: Int {
    // swiftlint:disable identifier_name
    case Normal = 1
    case Json = 2
    // swiftlint:enable identifier_name
}

enum CodeType: Int {
    //    | 200 | OK |请求成功| ✅ |
    //    | 400 | BAD_REQUEST |语义有误或参数错误|❎|
    //    | 401 | UNAUTHORIZED |未登录|❎|
    //    | 404 | NOT_FOUND |资源不存在|❎|
    //    | 403 | FORBIDDEN |用户未授权|❎|
    //    | 408 | TIMEOUT |请求超时|❎|
    //    | 409 | CONFLICT |资源存在重复或冲突|✅|
    //    | 429 | TOO_MANY_REQUESTS |请求过于频繁|❎|
    //    | 500 | SERVER_ERROR |服务异常|❎|
    //    | 600 | LOGIN_FAILED |登陆失败, 请检查输入的登陆信息是否正确|❎|
    //    | 601 | LOGIN_TIMEOUT |登陆信息已过期, 请重新登陆|❎|
    //    | 602 | LOGIN_DUPLICATED |您的账户已被其他用户登陆|❎|
    //    | 603 | LOGIN_DISABLE |登陆失败, 该账户已被禁用|❎|
    
    // swiftlint:disable identifier_name
    case OK = 200
    case BAD_REQUEST = 400
    case UNAUTHORIZED = 401
    case FORBIDDEN = 403
    case NOT_FOUND = 404
    case TIMEOUT = 408
    case CONFLICT = 409
    case TOO_MANY_REQUESTS = 429
    case SERVER_ERROR = 500
    case LOGIN_FAILED = 600
    
    case LOGIN_TIMEOUT = 601
    case LOGIN_DUPLICATED = 602
    
    case LOGIN_DISABLE = 603
    // swiftlint:enable identifier_name
}


// 后台返回接口基础信息
class ResponseBasicInformation: NSObject {
    @objc var message : String?
    @objc var success : Bool = false  // 旧接口
    @objc var error : Error?  // 框架报错
    var errorCode: ErrorCodeType?   // 后台返回 旧接口
    var code: CodeType?   // 新接口 code
    @objc var networkErrorMsg = "网络异常"
    var total: Int = 0  // 判断是否有更多数据
    
    
    //    ```json
    //    {
    //      "data": {
    //        "page": 1, // 前端传入的页码
    //        "total": 1000, // 分页插件给出的总数据量
    //        "list": [{
    //          // 这里面就是 A 类的结构
    //        }, {
    //        }]
    //      },
    //      "message": "请求成功", // string, 响应信息
    //      "code": "200", // string, 响应码
    //      "successful": true // boolean, 请求方用于判断是否处理成功的字段
    //    }
    
}

typealias CompletionHandle = (_ response: Dictionary<String,Any>?, _ responseInformation: ResponseBasicInformation) -> ()

class BBNetWorkService: NSObject {
    
    static let shared = BBNetWorkService()
    
    // 请求管理类
    let sessionManager: Alamofire.Session = {
        let configuration = URLSessionConfiguration.default
        configuration.timeoutIntervalForRequest = 15
        return Alamofire.Session(configuration: configuration)
    }()

    // 请求头
    let headers: HTTPHeaders = [
        "Accept": "application/json; text/json; text/javascript; text/html; text/xml; text/plain",
        "Content-Type": "application/x-www-form-urlencoded; charset=utf-8;text/html",
        "OSChannel" : "iOS",
        "req-agent" : "baibu_app",
        "app_version" : "\(Bundle.main.infoDictionary?["CFBundleShortVersionString"] ?? "")"


    ]
    
    let jsonHeaders: HTTPHeaders = [
        "Accept": "application/json; text/json; text/javascript; text/html; text/xml; text/plain; charset=UTF-8",
        "Content-Type": "application/json; charset=UTF-8",
        "OSChannel" : "iOS",
        "req-agent" : "baibu_app",
        "app_version" : "\(Bundle.main.infoDictionary?["CFBundleShortVersionString"] ?? "")"
    ]
    
    // 接口封装
    class func sendRequest(_ requestDataType:RequestDataType = .Normal, method:HTTPMethod, params:[String : Any], url:String, handle: @escaping CompletionHandle) -> () {
        var parameters = [String: Any]()
        
//        parameters["buyerNo"] = BSAPIClient.sharedInstance()?.buyerNo
//        parameters["ticket"] = BSAPIClient.sharedInstance()?.ticket
//        parameters["buyerId"] = BSAPIClient.sharedInstance()?.buyerId
//        parameters["token"] = BSAPIClient.sharedInstance()?.token
        for (key,value) in params {
            if key == "page" {
                parameters["pageNum"] = value
            }
            if key == "limit" {
                parameters["pageSize"] = value
            }
            
            if key == "pageNum" {
                parameters["page"] = value
            }
            if key == "pageSize" {
                parameters["limit"] = value
            }
            
            parameters[key] = value
        }
        SDLog("\n\n==================================开始开始==================================================")
        SDLog("访问URL  \(url)")
        SDLog("访问参数  \(parameters)")
        
        // 设置请求头
        var headers = BBNetWorkService.shared.headers
        if (requestDataType == .Normal) {
            SDLog("请求头  \(BBNetWorkService.shared.headers)")
            
        } else {
            SDLog("请求头  \(BBNetWorkService.shared.jsonHeaders)")
            headers = BBNetWorkService.shared.jsonHeaders
        }
        
        BBNetWorkService.shared.sessionManager.request(url, method: method, parameters: parameters, encoding: (requestDataType == .Normal) ? URLEncoding.default : JSONEncoding.default, headers: headers).responseJSON { (response) in
            

            
            switch response.result {
            case .success(let value):
                if let dict = value as? Dictionary<String,Any> {
                    
                    // message
                    let responseInformation = ResponseBasicInformation()
                    if let message = dict["message"] as? String {
                        responseInformation.message = message
                        
                    }
                    
                    // success
                    if let success = dict["success"] as? NSNumber {
                        if success.intValue == 1 {
                            responseInformation.success = true
                        } else {
                            responseInformation.success = false
                        }
                    }
                    
                    if let success = dict["successful"] as? NSNumber {
                        if success.intValue == 1 {
                            responseInformation.success = true
                        } else {
                            responseInformation.success = false
                        }
                    }
                    
                    // total
                    if let total = dict["total"] as? NSNumber {
                        responseInformation.total = total.intValue
                    }
                    
                    // error (后台返回的状态码  旧)
                    if let error = dict["error"] as? NSNumber {
                        responseInformation.errorCode = ErrorCodeType(rawValue: error.intValue)
                        BBNetWorkService.checkStatusCode(statusCode: responseInformation.errorCode)
                    }
                    
                    // code (后台返回的状态码  新)
                    if let error = dict["code"] as? NSNumber {
                        responseInformation.code = CodeType(rawValue: error.intValue)
                        BBNetWorkService.checkCode(statusCode: responseInformation.code)
                    }
                    

                    if let data  = try? JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted) {
                        guard let dataJson = String(data: data, encoding: String.Encoding.utf8) else {return}

//                        #if DEBUG
//                        BSAPIClient.sharedInstance()?.requestInfoView.textView?.text = ("-->请求头\n\(BBNetWorkService.shared.headers)-->请求路径\n\(url)\n-->请求参数\n\(params)\n-->返回结果\n\(String(describing: dataJson))\n==================================结尾")
//                        #else
//                        #endif

                        SDLog(dataJson as Any)
                        SDLog("结束结束=======================================================================")
                    }

                    handle(dict, responseInformation)
                    
                }
                
            case .failure(let error):

                SDLog(response)
                SDLog("结束结束=======================================================================")

                let responseInformation = ResponseBasicInformation()
                responseInformation.error = error
                handle(nil, responseInformation)
                
            }
        }
    }

}

//MARK: - 图片上传
extension BBNetWorkService {
    class func sendFileUploadRequest(_ requestDataType:RequestDataType = .Normal, method:HTTPMethod, params:[String : Any], fileArray: [Any], acceptImageDataKey: String , url:String, handle: @escaping CompletionHandle) -> () {
        var parameters = [String: Any]()

//        parameters["buyerNo"] = BSAPIClient.sharedInstance()?.buyerNo
//        parameters["ticket"] = BSAPIClient.sharedInstance()?.ticket
//        parameters["buyerId"] = BSAPIClient.sharedInstance()?.buyerId
//        parameters["token"] = BSAPIClient.sharedInstance()?.token
        for (key,value) in params {
            parameters[key] = value
        }

        SDLog("访问URL  \(url)")
        SDLog("访问参数  \(parameters)")

        // 设置请求头
        var headers = BBNetWorkService.shared.headers
        if (requestDataType == .Normal) {
            SDLog("请求头  \(BBNetWorkService.shared.headers)")

        } else {
            SDLog("请求头  \(BBNetWorkService.shared.jsonHeaders)")
            headers = BBNetWorkService.shared.jsonHeaders
        }

        let URL = try! URLRequest(url: url, method: method, headers: headers)  // swiftlint:disable:this force_try

        SDLog("\n\n==================================开始开始==================================================")
        let request =  BBNetWorkService.shared.sessionManager.upload(multipartFormData: { (multipartFormData) in
            
        }, with: URL);
        request.response { resp in
            switch resp.result {
            case .success(let data):
                
                break
            case .failure(let error): break
                
            }
        }
        
//        BBNetWorkService.shared.sessionManager.upload(multipartFormData: { (multipartFormData) in
//
//            // 拼接图片
//            for i in 0..<fileArray.count {
//                if let image = fileArray[i] as? UIImage {
//                    let imageData = image.jpegData(compressionQuality: 0.5)
//                    let formatter = DateFormatter()
//                    formatter.dateFormat = "yyyyMMddHHmmss"
//                    let timeStr = formatter.string(from: Date())
//                    let fileName = "\(timeStr)+\(i).png"
//                    SDLog("\(fileName)")
//                    multipartFormData.append(imageData!, withName: acceptImageDataKey, fileName: fileName, mimeType: "image/png")
//                }
//            }
//
//            // 拼接其他参数
//            for (key, value) in params {
//                let valueStr = "\(value)"
//                if let data = valueStr.data(using: String.Encoding.utf8) {
//                    multipartFormData.append( data, withName: key)
//                }
//            }
//
//        }, with: URL) { (result) in
//
//            switch result {
//            case .success(let upload, _, _):
//                //连接服务器成功后，对json的处理
//                upload.responseJSON { response in
//                    //解包
//
//                    if let value = response.result.value, let dict = value as? Dictionary<String,Any> {
//
//                        // message
//                        let responseInformation = ResponseBasicInformation()
//                        if let message = dict["message"] as? String {
//                            responseInformation.message = message
//
//                        }
//
//                        // success
//                        if let success = dict["success"] as? NSNumber {
//                            if success.intValue == 1 {
//                                responseInformation.success = true
//                            } else {
//                                responseInformation.success = false
//                            }
//                        }
//
//                        if let success = dict["successful"] as? NSNumber {
//                            if success.intValue == 1 {
//                                responseInformation.success = true
//                            } else {
//                                responseInformation.success = false
//                            }
//                        }
//
//                        // error (后台返回的状态码  旧)
//                        if let error = dict["error"] as? NSNumber {
//                            responseInformation.errorCode = ErrorCodeType(rawValue: error.intValue)
//                            BBNetWorkService.checkStatusCode(statusCode: responseInformation.errorCode)
//                        }
//
//                        // code (后台返回的状态码  新)
//                        if let error = dict["code"] as? NSNumber {
//                            responseInformation.code = CodeType(rawValue: error.intValue)
//                            BBNetWorkService.checkCode(statusCode: responseInformation.code)
//                        }
//
//                        handle(dict, responseInformation)
//
//                        guard let data = try? JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted) else {return}
//                        guard let dataJson = String(data: data, encoding: String.Encoding.utf8) else {return}
//
//                        #if DEBUG
//                        BSAPIClient.sharedInstance()?.requestInfoView.textView?.text = ("-->请求头\n\(BBNetWorkService.shared.headers)-->请求路径\n\(url)\n-->请求参数\n\(params)\n-->返回结果\n\(String(describing: dataJson))\n==================================结尾")
//                        #else
//                        #endif
//
//                        SDLog(dataJson as Any)
//                        SDLog("结束结束=======================================================================")
//
//
//                    } else {
//                       let responseInformation = ResponseBasicInformation()
//                       responseInformation.error = response.error
//                       responseInformation.networkErrorMsg = "请求超时"
//                       handle(nil, responseInformation)
//                   }
//                }
//                //获取上传进度
//                upload.uploadProgress(queue: DispatchQueue.global(qos: .utility)) { progress in
//                    SDLog("图片上传进度: \(progress.fractionCompleted)")
//                    SDLog("图片上传进度:=======================================================================")
//                }
//            case .failure(let error):
//                let responseInformation = ResponseBasicInformation()
//                responseInformation.error = error
//                handle(nil, responseInformation)
//
//                SDLog(result)
//
//                SDLog("结束结束=======================================================================")
//            }
//        }

    }
    
}

//MARK: - 处理新接口返回状态码
extension BBNetWorkService {
    class func checkCode(statusCode: CodeType?) {
        
        let title = "百布系统提示"
        var message = ""
        var btnTitle = ""
        
        if (statusCode == .FORBIDDEN) {
            //                    message = "用户未授权！\r\n请重新登录。"
            //                    btnTitle = "确定"
            
        } else if (statusCode == .LOGIN_DUPLICATED) {
            message = "您的帐号已经在别处登录！\r\n请重新登录。"
            btnTitle = "确定"
            
        } else if (statusCode == .LOGIN_TIMEOUT) {
            message = "登录信息已过期！\r\n请重新登录。"
            btnTitle = "确定"
            
        } else {
            //                MBProgressHUD.showError(message
            return
        }
        
//        Alert.showView(withTitle: title, message: message, dismiss: { (index) in
//            if index == 0 {
//                BBNetWorkService.jumpLogin()
//            }
//        }, cancelButtonIndex: 0, titles: [btnTitle])
        
    }
    
//    class func jumpLogin() {
//        BBLoginTool.clearLoginInfo()
//        if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
//            let vc = XMLoginViewController()
//            let nv = DEMONavigationController(rootViewController: vc)
//            appDelegate.window?.rootViewController?.present(nv, animated: true, completion: nil)
//        }
//    }
    
}

//MARK: - 处理旧接口返回状态码
extension BBNetWorkService {
    class func checkStatusCode(statusCode: ErrorCodeType?) {
        
        let title = "百布系统提示"
        var message = ""
        var btnTitle = ""
        
        if (statusCode == .unauthorized) {
            message = "用户未授权！\r\n请重新登录。"
            btnTitle = "确定"
            
        } else if (statusCode == .accountAbnormal) {
            message = "您的账户状态不正常！"
            btnTitle = "马上联系客服"
            
        } else if (statusCode == .multiDeviceLogin) {
            message = "您的帐号已经在别处登录！\r\n请重新登录。"
            btnTitle = "确定"
            
        } else if (statusCode == .loginInformationOutdate) {
            message = "您的帐号已经在别处登录！\r\n请重新登录。"
            btnTitle = "确定"
            
        } else {
            //                MBProgressHUD.showError(message
            return
        }
        
//        Alert.showView(withTitle: title, message: message, dismiss: { (index) in
//            if index == 0 {
//                BBNetWorkService.jumpLogin()
//            }
//        }, cancelButtonIndex: 0, titles: [btnTitle])
        
    }
    
}
